﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmallestDifferenceBetweenArrays
{
    /// <summary>
    /// You have two arrays of integers, where the integers do not repeat and the two arrays have no common integers. 
    /// Let x be any integer in the first array, y any integer in the second. Find min(Abs(x-y)). 
    /// That is, find the smallest difference between any of the integers in the two arrays. 
    /// 
    /// Assumptions: Assume both arrays are sorted in ascending order.
    /// 
    /// http://www.careercup.com/question?id=5140428923863040
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            int[] array1 = { 0, 1, 2, 3, 4 };
            int[] array2 = { 5, 6, 7, 8, 9 };

            int[] array3 = { 2, 4, 6, 7, 9 };
            int[] array4 = { 0, 1, 3, 5, 8 };

            int result = GetDifference(array3, array4);

            Console.WriteLine(result);

            Console.Read();
        }

        public static int GetDifference(int[] array1, int[] array2)
        {
            int min = int.MaxValue;
            int count = 0;

            for (int i = 0; i < array1.Length; i++)
            {
                for (int j = 0; j < array2.Length; j++)
                {
                    int temp;

                    if (array1[i] < array2[j])
                        temp = array2[j] - array1[i];
                    else
                        temp = array1[i] - array2[j];

                    if (temp < min)
                        min = temp;

                    count++;

                    if (min == 1)
                        break;
                }
            }

            Console.WriteLine("Total Iterations: {0}", count);

            return min;
        }

        public static int GetDifferenceOptimized(int[] array1, int[] array2)
        {
            int result = 0;

            int count = 0;

            int i = 0;
            int j = 0;

            while (i<array1.Length && j < array2.Length)
            {
                if (array1[i] < array2[j])
                {
                    result = array2[j] - array1[i];
                    i++;
                }
                else
                {
                    result = array1[i] - array2[j];
                    j++;
                }

                count++;

                if (result == 1)
                    break;
            }

            Console.WriteLine("Total Iterations: {0}", count);

            return result;

        }
    }
}
